package sg.edu.nus.comp.cs4218.impl.fileutils;

import java.io.File;
import java.nio.file.Files;

import sg.edu.nus.comp.cs4218.fileutils.IMoveTool;
import sg.edu.nus.comp.cs4218.impl.ATool;
import sg.edu.nus.comp.cs4218.impl.Shell;

public class MoveTool extends ATool implements IMoveTool {

	private String message;

	/**
	 * Constructor
	 * 
	 * @param arguments
	 *            - Arguments the tool is going to be executed with.
	 */
	public MoveTool(String[] arguments) {
		super(arguments);
		setStatusCode(0);
	}

	/**
	 * Moves the specified file to the specified destination
	 * 
	 * @param from
	 *           - The file to be moved
	 * @param to
	 *           - The destination for the file to be moved to
	 * @return true if and only if the file is successfully moved; false
	 *         otherwise
	 */
	@Override
	public boolean move(File from, File to) {
		try {
			File toTemp = to;
			if (toTemp.isDirectory()) { // if to is pointing to a directory
				toTemp = new File(toTemp.getCanonicalPath(), from.getName());
			}
			Files.move(from.toPath(), toTemp.toPath());

			message = "File has been moved";
			return true;
		} catch (Exception e) {
			message = "Unable to move file";
			setStatusCode(1);
			return false;
		}
	}

	/**
	 * Moves a file to a specified location
	 * 
	 * @param stdin
	 *            - Input on stdin. NOT THE ARGUMENTS! Can be null.
	 * @return Output on stdout
	 */
	@Override
	public String execute(File workingDir, String stdin) {
		if (super.args == null) {
			setStatusCode(1);
			message = "Invalid move command";
		}

		if (getStatusCode() == 0) {
			if (super.args.length >= 2) {
				File from = null;
				File to = null;
				
				if (super.args[0].equals("-") == false) {
					from = Shell.getFile(workingDir, super.args[0]);
				}
				else {
					if (stdin != null) {
						from = Shell.getFile(workingDir, stdin);
					}
					else {
						setStatusCode(1);
						message = "Invalid copy command";
					}
				}
								
				if (super.args[1].equals("-") == false) {
					to = Shell.getFile(workingDir, args[1]);
				}
				else {
					if (stdin != null) {
						to = Shell.getFile(workingDir, stdin);
					}
					else {
						setStatusCode(1);
						message = "Invalid copy command";
					}
				}
				move(from, to);
			} else {
				setStatusCode(1);
				message = "Invalid move command";
			}
		}

		return message;
	}
}